<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/11
 * Time: 17:20
 */
namespace core\log;

use core\Config;

class Log
{
    protected static $instance;
    private $format;
    private $logConfig;
    private $cutting_unit;
    private $cutting_size;
    private $f;

    public function __construct()
    {
        $this->init();
    }

    public function init()
    {
        $config = Config::getInstance();
        $this->logConfig = $config->getConfig('log');
        $rootPath = $this->logConfig['log_path'];
        if (!is_dir($rootPath)){
            mkdir($rootPath,755,true);
        }
        $scale = substr($this->logConfig['file_cutting_size'],-1);
        $this->setScale($scale);
        $this->cutting_size = substr($this->logConfig['file_cutting_size'],0,strlen($this->logConfig['file_cutting_size'])-1);


        $logFileName = date('Y-m-d').'.log';
        $logFileAllName = $rootPath.$logFileName;
        if (is_file($logFileAllName) && filesize($logFileAllName) * $this->cutting_unit > $this->cutting_size){
            copy($logFileAllName,$rootPath.time().$logFileName);
            unlink($logFileAllName);unset($rootPath);unset($logFileName);
        }
        if (is_file($logFileAllName)){
            $this->f = fopen($logFileAllName,'a+');
        }else{
            $this->f = fopen($logFileAllName,'w+');
        }
        fwrite($this->f,'----------------------------------------------------------------------'."\r\n");
    }

    /**
     * 获取单例
     * @return Log
     */
    public static function getInstance()
    {
        if (is_null(self::$instance)){
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function log($value,$name = 'log')
    {
        if (is_array($value) || is_object($value)){
            $value = json_encode($value);
        }
            fwrite($this->f,"[$name] ".$value."\r\n");
    }

    public function setScale($scale)
    {
        switch ($scale){
            case 'k':
            case 'K':$this->cutting_unit = 1 / 1024;
                break;
            case 'm':
            case 'M':$this->cutting_unit = 1 / 1024 / 1024;
                break;
            case 'g':
            case 'G':$this->cutting_unit = 1 / 1024 / 1024 / 1024;
                break;
            default:
        }
    }

    public function __destruct()
    {
        fclose($this->f);
    }
}